package org.pussinboots.morning.cms.controller.product;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.pussinboots.morning.cms.common.result.CmsPageResult;
import org.pussinboots.morning.cms.common.result.CmsResult;
import org.pussinboots.morning.cms.common.security.AuthorizingUser;
import org.pussinboots.morning.cms.common.util.ServletUtils;
import org.pussinboots.morning.cms.common.util.SingletonLoginUtils;
import org.pussinboots.morning.common.base.BaseController;
import org.pussinboots.morning.common.base.BasePageDTO;
import org.pussinboots.morning.common.constant.CommonReturnCode;
import org.pussinboots.morning.common.enums.StatusEnum;
import org.pussinboots.morning.common.enums.WebSiteFileBelongEnum;
import org.pussinboots.morning.common.support.page.PageInfo;
import org.pussinboots.morning.common.support.upload.UploadManager;
import org.pussinboots.morning.common.support.upload.UploadResult;
import org.pussinboots.morning.product.entity.Category;
import org.pussinboots.morning.product.entity.Product;
import org.pussinboots.morning.product.pojo.vo.ProductVO;
import org.pussinboots.morning.product.service.ICategoryService;
import org.pussinboots.morning.product.service.IProductCategoryService;
import org.pussinboots.morning.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 *
 */
@Controller
@RequestMapping(value = "/product")
@Api(value = "产品管理")
public class ProductController extends BaseController {

    @Autowired
    private IProductService iProductService;

    @Autowired
    private ICategoryService iCategoryService;

    /**
     * GET 产品管理界面
     *
     * @return
     */
    @ApiOperation(value = "产品管理界面", notes = "产品管理界面")
    @RequiresPermissions("product:list:view")
    @GetMapping(value = "/view")
    public String getProductPage(Model model) {
        return "/modules/product/product_list";
    }

    /**
     * GET 产品列表
     *
     * @return
     */
    @ApiOperation(value = "获取分类列表", notes = "根据分页信息/搜索内容/父产品ID获取分类列表")
    @RequiresPermissions("product:list:view")
    @GetMapping(value = "/list")
    @ResponseBody
    public Object listproduct(PageInfo pageInfo, @RequestParam(required = false, value = "search") String search) {
        BasePageDTO<Product> basePageDTO = null;
        try {
            basePageDTO = iProductService.listByPage(pageInfo, search);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String s = JSON.toJSONString(basePageDTO.getList());
        return new CmsPageResult(basePageDTO.getList(), basePageDTO.getPageInfo().getTotal());
    }

    /**
     * GET 更新产品页面
     *
     * @return
     */
    @ApiOperation(value = "更新产品页面", notes = "更新产品页面")
    @RequiresPermissions("product:list:edit")
    @GetMapping(value = "/{productId}/edit")
    public String getUpdatePage(Model model, @PathVariable("productId") Long productId) {
        // 产品信息
        Product product = iProductService.selectById(productId);
        List<Category> categoryList = iCategoryService.listUpperByProductId(productId, StatusEnum.SHOW.getStatus());
        if(!CollectionUtils.isEmpty(categoryList)){
            StringBuilder categoryName = new StringBuilder();
            StringBuilder categoryIds = new StringBuilder();
            for (int i = 0; i < categoryList.size(); i++) {
                categoryName.append(categoryList.get(i).getName()).append(",");
                categoryIds.append(categoryList.get(i).getCategoryId()).append(",");
            }
            model.addAttribute("categoryName", categoryName.substring(0, categoryName.length() - 1));
            model.addAttribute("categoryIds", categoryIds.substring(0, categoryIds.length() - 1));
        }
        model.addAttribute("product", product);

        return "/modules/product/product_list_edit";
    }

    /**
     * PUT 更新产品信息
     *
     * @return
     */
    @ApiOperation(value = "更新产品信息", notes = "根据url产品ID来指定更新对象,并根据传过来的产品信息来更新产品信息")
    @RequiresPermissions("product:list:edit")
    @PutMapping(value = "/{productId}/edit")
    @ResponseBody
    public Object update(Product product, @PathVariable("productId") Long productId,
                         @RequestParam(value = "showInNav", defaultValue = "0") Integer showInNav,
                         @RequestParam(value = "showInTop", defaultValue = "0") Integer showInTop,
                         @RequestParam(value = "showInHot", defaultValue = "0") Integer showInHot,
                         @RequestParam(value = "showInShelve", defaultValue = "0") Integer showInShelve,
                         @RequestParam(value = "categoryId") Long categoryId) {

        AuthorizingUser authorizingUser = SingletonLoginUtils.getUser();
        if (authorizingUser != null) {
            // 更新用户及产品记录
            product.setShowInHot(showInHot);
            product.setShowInNav(showInNav);
            product.setShowInTop(showInTop);
            product.setShowInShelve(showInShelve);
            Integer count = iProductService.updateProduct(product,categoryId);
            return new CmsResult(CommonReturnCode.SUCCESS, count);
        } else {
            return new CmsResult(CommonReturnCode.UNAUTHORIZED);
        }
    }

    /**
     * GET 创建产品页面
     *
     * @return
     */
    @ApiOperation(value = "创建产品页面", notes = "创建产品页面")
    @RequiresPermissions("product:list:add")
    @GetMapping(value = "/list/create")
    public String getCreatePage(Model model) {
        return "/modules/product/product_list_create";
    }

    /**
     * POST 创建产品
     *
     * @return
     */
    @ApiOperation(value = "创建产品", notes = "创建产品")
    @RequiresPermissions("product:list:add")
    @PostMapping(value = "/create")
    @ResponseBody
    public Object insert(Product product, @RequestParam(value = "categoryId") Long categoryId) {
        AuthorizingUser authorizingUser = SingletonLoginUtils.getUser();
        if (authorizingUser != null) {
            // TODO 对产品名称进行唯一性校验
            product.setProductNumber(System.currentTimeMillis());
            boolean count = iProductService.insertProductInfo(authorizingUser.getUserName(), product, categoryId);
            return new CmsResult(CommonReturnCode.SUCCESS, count);
        } else {
            return new CmsResult(CommonReturnCode.UNAUTHORIZED);
        }
    }


}
